<template> 
  <div class="app-container">
    <div class="table-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="输入搜索:">
          <el-input v-model="listQuery.keyword" placeholder="帐号/姓名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearchList">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            style="float:right"
            @click="handleResetSearch()"
          >
            重置
          </el-button>
        </el-form-item>

        <el-button type="primary" style="float: right;" @click="handleAdd">添加</el-button>
      </el-form>
      <el-table ref="adminTable"
                :data="list"
                v-loading="listLoading" border
                :header-cell-style="tableHeaderColor">
        <el-table-column label="用户id" width="100" align="center">
          <template slot-scope="scope">{{scope.row.userId}}</template>
        </el-table-column>
        <el-table-column label="帐号" align="center">
          <template slot-scope="scope">{{scope.row.username}}</template>
        </el-table-column>
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">{{scope.row.nickname}}</template>
        </el-table-column>
        <el-table-column label="密码" align="center">
          <template slot-scope="scope">{{scope.row.password}}</template>
        </el-table-column>
        <el-table-column label="添加时间" width="160" align="center">
          <template slot-scope="scope">{{scope.row.createDate | formatDateTime}}</template>
        </el-table-column>
        <el-table-column label="最后登录" width="160" align="center">
          <template slot-scope="scope">{{scope.row.updateDate | formatDateTime}}</template>
        </el-table-column>
        <el-table-column label="是否启用" width="140" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleStatusChange(scope.$index, scope.row)"
              :active-value="0"
              :inactive-value="1"
              v-model="scope.row.status">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button size="mini"
                       icon="el-icon-star-off"
                       type="warning" round
                       @click="handleSelectRole(scope.$index, scope.row)">分配角色
            </el-button>
            <el-button size="mini"
                       icon="el-icon-edit"
                       type="primary" round
                       @click="handleUpdate(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button size="mini"
                       icon="el-icon-delete"
                       type="danger" round
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit?'编辑用户':'添加用户'"
      :visible.sync="dialogVisible"
      width="40%">
      <el-form :model="admin"
               ref="adminForm"
               label-width="150px" size="small">
        <el-form-item label="帐号：" prop="username"  :rules="[
            { required: true, message: '请输入账号', trigger: 'blur' },
            {min: 4, max: 18, message: '长度在 4 到 18 个字符', trigger: 'blur'}
          ]">
          <el-input v-model="admin.username" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="nickname" :rules="[
            { required: true, message: '请输入姓名', trigger: 'blur' },
            {min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur'}
          ]">
          <el-input v-model="admin.nickname" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password" :rules="[
            { required: true, message: '请输入密码', trigger: 'blur' }
          ]">
          <el-input v-model="admin.password"  style="width: 250px"></el-input>
        </el-form-item>
        <!--        <el-form-item label="备注：">-->
        <!--          <el-input v-model="admin.note"-->
        <!--                    type="textarea"-->
        <!--                    :rows="5"-->
        <!--                    style="width: 250px"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="是否启用：">
          <el-radio-group v-model="admin.status">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm('adminForm')" size="small">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="allocDialogVisible"
      width="30%">
      <el-select v-model="allocRoleIds" multiple placeholder="请选择" size="small" style="width: 80%">
        <el-option
          v-for="item in allRoleList"
          :key="item.roleId"
          :label="item.name"
          :value="item.roleId">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleAllocDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {allocRole, delUser, listUser, saveUser, updateStatus, listRoles} from '@/api/user';
  import {formatDate} from '@/utils/date';

  const defaultListQuery = {
    pageNum: 1,
    pageSize: 10,
    keyword: null
  };
  const defaultAdmin = {
    userId: null,
    username: null,
    password: null,
    nickname: null,
    email: null,
    note: null,
    status: 0
  };
  export default {
    name: 'adminList',
    data() {
      return {
        listQuery: Object.assign({}, defaultListQuery),
        list: null,
        total: null,
        listLoading: false,
        dialogVisible: false,
        admin: Object.assign({}, defaultAdmin),
        isEdit: false,
        allocDialogVisible: false,
        allocRoleIds: [],
        allRoleList: [],
        allocAdminId: null
      }
    },
    created() {
      this.getList();
      this.getAllRoleList();
    },
    filters: {
      formatDateTime(time) {
        if (time == null || time === '') {
          return 'N/A';
        }
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    methods: {
      tableHeaderColor({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return "background-color:#efefef;color:#333";
        }
      },
      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      handleAdd() {
        this.dialogVisible = true;
        this.isEdit = false;
        this.admin = Object.assign({}, defaultAdmin);
        if(this.$refs['adminForm'] !== undefined){
          this.$refs['adminForm'].resetFields();
        }

      },
      handleStatusChange(index, row) {
        this.$confirm('是否要修改该状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let reqUser = {
            userId: row.userId,
            status: row.status
          };
          updateStatus(reqUser).then(response => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消修改'
          });
          this.getList();
        });
      },
      handleDelete(index, row) {
        this.$confirm('是否要删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUser(row.userId).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          });
        }).catch(() => {
        });;
      },
      handleUpdate(index, row) {
        this.dialogVisible = true;
        this.isEdit = true;
        if(this.$refs['adminForm'] !== undefined){
          this.$refs['adminForm'].resetFields();
        }
        this.admin = Object.assign({}, row);
      },
      handleDialogConfirm(formName) {

        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否要确认?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              saveUser(this.admin).then(response => {
                this.$message({
                  message: '操作成功！',
                  type: 'success'
                });
                this.dialogVisible = false;
                this.getList();
              })
            }).catch(() => {
            });
          }
        });
      },
      handleAllocDialogConfirm() {
        this.$confirm('是否要确认?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let roleIds = '';
          if(this.allocRoleIds.length > 0){
            roleIds = this.allocRoleIds.join(",");
          }

          let data ={
            userId: this.allocAdminId,
            roleIds: roleIds
          }
          allocRole(data).then(response => {
            this.$message({
              message: '分配成功！',
              type: 'success'
            });
            this.allocDialogVisible = false;
            this.getList();
          })
        }).catch(() => {
        });
      },
      handleSelectRole(index, row) {
        this.allocAdminId = row.userId;
        this.allocDialogVisible = true;
        this.getRoleListByAdmin(row);
      },
      getList() {
        this.listLoading = true;
        listUser(this.listQuery).then(response => {
          this.listLoading = false;
          this.list = response.data.records;
          this.total = response.data.total;
        });
      },
      getAllRoleList() {
        listRoles().then(response => {
          this.allRoleList = response.data;
        });
      },
      getRoleListByAdmin(row) {
        this.allocRoleIds = [];
        if (row.roleIds != null && row.roleIds.length > 0) {
          this.allocRoleIds = row.roleIds.split(",");
          this.allocRoleIds = this.allocRoleIds.map((value)=>{
            return parseInt(value)
          })
        }
      }
    }
  }
</script>
<style></style>


